package psql

import (
	"database/sql"
	"fmt"
	global_util "gitee.com/cheneylau/components/web-server/global/global-util"
	"github.com/astaxie/beego/orm"
	_ "github.com/lib/pq"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"log"
	"time"
)

var BeegoDB orm.Ormer
var GormDB *gorm.DB

func init() {
	initPGSQL()
	initGormDB()
}

func getDsn() string {
	cnf, err := global_util.AppConfig()
	runmode := cnf.String("runmode")
	dbHost := cnf.String(runmode+"::psql_db_host")
	dbPort := cnf.String(runmode+"::psql_db_port")
	dbUser := cnf.String(runmode+"::psql_db_user")
	dbPassword := cnf.String(runmode+"::psql_db_password")
	dbName := cnf.String(runmode+"::psql_db_name")
	global_util.CheckErr(err, "ini config not exist!")
	if dbHost == "" {
		log.Println("PGSQL未配置，如需要，在app.conf中配置！")
		return ""
	}

	url := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=disable",dbUser,dbPassword,dbHost,dbPort,dbName)
	return url
}

func initPGSQL()  {
	orm.RegisterDataBase("default", "postgres",getDsn() , 30)

	// register model
	//orm.RegisterModel()

	// create table
	//orm.RunSyncdb("pgsql", false, true)
	// debug sql
	//orm.Debug = true

	BeegoDB = orm.NewOrm()
	BeegoDB.Using("pgsql")
}

func initGormDB()  {
	db1, err := sql.Open("postgres", getDsn())
	if err != nil {
		panic(err)
	}
	gormDB, err := gorm.Open(postgres.New(postgres.Config{
		Conn: db1,
	}), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	sqlDB, _ := gormDB.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)
	GormDB = gormDB
}
